package dxunderground.utilities.ocr;

import java.awt.Color;

import java.awt.image.BufferedImage;
import java.awt.image.ColorModel;
import java.awt.image.Raster;
import java.util.List;

public class BufferedImageUtility {
	/**
	 * Trims the image down to its smallest size.
	 * 
	 * @param sampleImage
	 * @return
	 */
	public static CaptchaImage trimImage(CaptchaImage sampleImage) {
		int fromTop, fromBottom, fromLeft, fromRight;
		boolean end = false;
		for (fromTop = 0; fromTop < sampleImage.getHeight() && !end; fromTop++) {
			Byte[] line = sampleImage.getValue()[fromTop];
			for (Byte b : line) {
				if (b != 0) {
					end = true;
					fromTop--;
					break;
				}
			}
		}
		end = false;
		for (fromBottom = sampleImage.getHeight() - 1; fromBottom > 0 && !end; fromBottom--) {
			Byte[] line = sampleImage.getValue()[fromBottom];
			for (Byte b : line) {
				if (b != 0) {
					end = true;
					fromBottom++;
					break;
				}
			}
		}
		end = false;
		for (fromLeft = 0; fromLeft < sampleImage.getWidth() && !end; fromLeft++) {
			for (int i = 0; i < sampleImage.getHeight(); i++) {
				if (sampleImage.getValue()[i][fromLeft] != 0) {
					end = true;
					fromLeft--;
					break;
				}
			}
		}
		end = false;
		for (fromRight = sampleImage.getWidth() - 1; fromRight > 0 && !end; fromRight--) {
			for (int i = 0; i < sampleImage.getHeight(); i++) {
				if (sampleImage.getValue()[i][fromRight] != 0) {
					end = true;
					fromRight++;
					break;
				}
			}
		}

		return sampleImage.Chop(fromTop, fromLeft, sampleImage.getWidth() - fromLeft - (sampleImage.getWidth() - 1 - fromRight), sampleImage.getHeight() - fromTop - (sampleImage.getHeight() - 1 - fromBottom));
	}

	public static CaptchaImage BinarizateToSampleImage(BufferedImage img, List<Color> ignoredColours) {
		// TODO optimize this
		Byte[][] value = new Byte[img.getHeight()][img.getWidth()];
		Raster raster = img.getRaster();
		ColorModel colorModel = img.getColorModel();

		for (int i = 0; i < img.getHeight(); i++) {
			for (int j = 0; j < img.getWidth(); j++) {
				Object obj = raster.getDataElements(j, i, null);
				for (Color colour : ignoredColours) {
					if (colorModel.getRed(obj) == colour.getRed() && colorModel.getGreen(obj) == colour.getGreen() && colorModel.getBlue(obj) == colour.getBlue()) {
						value[i][j] = 0;
						break;
					} else
						value[i][j] = 1;
				}
			}
		}
		return new CaptchaImage(value);
	}
}
